package com.hj.ipproxy.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.hj.ipproxy.handler.FetchIpHandler;
import com.hj.tools.PropertiesUtil;
/**
 * 配置管理
 * @author HJ
 */
public class ConfigrurationMgr {
	public static final String CONFIG_PATH = "/config/config.properties";
	private static final String KEY_IP_VALIDATE_URL = "ip_validate_url";
	private static final String KEY_FETCHIPHANDLERS = "fetch_ip_handlers";
	private static final String PREFIX_CLASS_NAME = "com.hj.ipproxy.handler.";
	private static final String SUFFIX_CLASS_NAME = "Handler";
	private static Properties props;
	private static final Map<String, FetchIpHandler> fetchIpHandlers = new HashMap<String, FetchIpHandler>();
	private static int handlerTotal = 0;
	// 私有构造函数
	private ConfigrurationMgr(){}
	
	static{
		props = PropertiesUtil.getProperties(CONFIG_PATH);
		regHandler();
	}

	public static int getHandlerTotal(){
		return handlerTotal;
	}
	
	private static void regHandler(){
		try {
			String[] ipHandlers = PropertiesUtil.vtoArray(props, KEY_FETCHIPHANDLERS);
			for (String classname : ipHandlers) {
				String allClassName = PREFIX_CLASS_NAME+classname+SUFFIX_CLASS_NAME;
				if (fetchIpHandlers.get(allClassName)==null) {
					FetchIpHandler f = (FetchIpHandler)Class.forName(allClassName).newInstance();
					fetchIpHandlers.put(allClassName, f);
					handlerTotal++;
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
	public static Map<String, FetchIpHandler> getFetchHandler(){
		return fetchIpHandlers;
	}
	
	public static String getValidateUrl(){
		return props.getProperty(KEY_IP_VALIDATE_URL);
	}
}
